package com.cssw.fyzb.core.dao.adnumprice;


import com.cssw.fyzb.core.model.dodb.AdNumPrice;
import com.cssw.fyzb.core.model.dodb.AdNumPriceLog;
import com.cssw.fyzb.core.model.dodb.UserExt;
import com.cssw.fyzb.core.util.TimeUtil;
import com.ydn.dbframe.plugin.activerecord.Db;
import com.ydn.dbframe.plugin.activerecord.parse.SqlParse;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 */
@Repository
public class AdNumPriceDaoImpl implements AdNumPriceDao {

    @Override
    public AdNumPriceLog getAdNumPriceLog(Long userId) {
        int dayTime = TimeUtil.getTimeYYMMDD(new Date());
        Map<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        param.put("dayTime", dayTime);
        SqlParse sqlParse = new SqlParse(param);
        sqlParse.addSQL("SELECT * FROM t_ad_num_price_log ");
        sqlParse.addSQL(" WHERE user_id=:userId AND day_time=:dayTime ");
        return AdNumPriceLog.dao.findFirst(sqlParse);
    }

    @Override
    public AdNumPrice getConfig(int num) {
        Map<String, Object> param = new HashMap<>();
        SqlParse sqlParse = new SqlParse(param);
        param.put("num", num);
        sqlParse.addSQL("SELECT * FROM t_ad_num_price ");
        sqlParse.addSQL(" WHERE num=:num");
        return AdNumPrice.dao.findFirst(sqlParse);
    }

    @Override
    public Boolean addPrice(Long userId,BigDecimal price) {
        UserExt userExt = UserExt.dao.findById(userId);
        BigDecimal gzAddPrice = userExt.getGzAddPrice() == null ? BigDecimal.ZERO : userExt.getGzAddPrice();
        userExt.setGzAddPrice(gzAddPrice.add(price));
        return userExt.update();
    }

    @Override
    public List<AdNumPrice> list() {
        StringBuffer sql = new StringBuffer();
        sql.append("select * from t_ad_num_price order by sort ");
        return AdNumPrice.dao.find(sql.toString());
    }

    @Override
    public void updateNum(Long numId, Integer num) {
        AdNumPriceLog log = new AdNumPriceLog();
        log.setNum(num);
        log.setLogId(numId);
        log.update();
    }


    @Override
    public void updateLog(AdNumPriceLog log) {
        log.update();
    }

    @Override
    public Long saveLog(Long userId, Integer num, BigDecimal price) {
        int dayTime = TimeUtil.getTimeYYMMDD(new Date());
        AdNumPriceLog adNumPriceLog = new AdNumPriceLog();
        adNumPriceLog.setUserId(userId);
        adNumPriceLog.setDayTime(dayTime);
        adNumPriceLog.setNum(1);
        if (null != price) {
            adNumPriceLog.setPrice(price);
        } else {
            adNumPriceLog.setPrice(BigDecimal.ZERO);
        }
        adNumPriceLog.setCreateTime(new Date());
        adNumPriceLog.save();
        return adNumPriceLog.getLogId();
    }
}
